package com.hltx.interceptor;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hltx.pojo.user.User;
import com.hltx.resolver.DefiniteException;
import com.hltx.util.ResultInfo;


public class WapSecurityInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		response.setContentType("text/html;charset=UTF-8");
		User user = (User) request.getSession().getAttribute(
				"sessionUser");
		if (user == null) {
			// 是否是AJAX登陆
			String requestType = request.getHeader("X-Requested-With");
			String forward = request.getServletPath();
			if (UrlConstant.urlMap.containsKey(forward)) {
				forward = UrlConstant.urlMap.get(forward);
			}
			String params = request.getQueryString();
			if(!StringUtils.isEmpty(params)){
				forward +="?"+URLEncoder.encode(params, "UTF-8");
			}
			String contextPath = request.getContextPath();
			if (!StringUtils.equals(requestType,"XMLHttpRequest")) {
				if (StringUtils.isEmpty(forward)) {
					response.sendRedirect(contextPath+"/toLogin");
				} else {
					response.sendRedirect(contextPath+"/toLogin?forward="+forward);
				}
			}else{
				Map<String, Object> resMap = new HashMap<String, Object>();
				resMap.put("result", this.initResult(ResultInfo.ERROR, "loginOut", "用户未登录","/toLogin"));
				ObjectMapper om = new ObjectMapper();
				response.getWriter().print(om.writeValueAsString(resMap));
			}
			return false;
		}
		if (!"1".equals(user.getState())) {
			String msg = "该用户已已经被禁用，请联系管理员";
			throw new DefiniteException(msg); 
		}

		return true;
	}
	
	public ResultInfo initResult(String state, String code, String message,String url){
		ResultInfo ri = new ResultInfo();
		ri.setState(state);
		ri.setCode(code);
		ri.setMessage(message);
		ri.setUrl(url);
		return ri;
	}
}
